Online-Academy

Look, Read, Understand, Apply

Menu

Data Structure

Dynamic Queue

Queue is a data structure in which elements are added or inserted from end called rear and elements are removed from another end called front. In queue First element inserted is the first element to be removed. So, Queue is also known as First In First Out (FIFO) Data structure. Queue can be static or dynamic. If queue is implemented in array then it will be static queue. If queue is implemented using concept of linked list then it will be dynamic queue.

Here, is a code to implement queue dynamically. A node contained data field (here, string), and address field is defined. Three objects of node class is created: objects are temp, front, and rear. Both rear and front are assigned null. Object of Scanner is created to take data for node and for provided value action to perform. This is a menu driven program. Users can insert, remove and view contents of queue. Menu is written inside while loop so, user can run loop as s/he likes.

case 1 is for adding or inserting elements to the queue. if rear is null then queue is empty.
case 2 is for removing element from the queue.
case 3 is for displaying content of queue
*/

import java.util.*; 
class dynamicQueue{
	public static void main(String args[]){
		node temp, front=null,rear=null;
		System.out.println("Creating Dynamic Queue!!!");
		int choice;
		String str; 
		Scanner sc = new Scanner(System.in);
		
		while(true){
			System.out.println("\n1.Insert\n2.Remove\n3.Show\nChoice:");
			choice = sc.nextInt();
			switch(choice){
				case 1: System.out.println("Enter Data:");
						str = sc.nextLine();
					    str = sc.nextLine();
						temp = new node();
						temp.data = str;
						temp.address = null; 
						if(rear == null){
							rear = temp;
							front = temp;
						}else{
							rear.address = temp;
							rear = temp;
						}
				break;
				case 2: System.out.println("Removing Element From Queue!!!");
						System.out.println("Element Removed : "+front.data);
						if(front == rear)
							System.out.println("Queue is Empty");
						else{
							temp = front;
							front = front.address;
							temp = null; 
						}
							
				break;
				case 3: System.out.println("Show contents of Queue: \n");
						for(temp=front;temp!=rear;temp=temp.address){
							System.out.print(temp.data+"  ");
						}
							System.out.print(temp.data+"  ");
				break;
				case 4: System.exit(0);
				break; 
			}
		}
	}
}
//Output:
Creating Dynamic Queue!!!

1.Insert
2.Remove
3.Show
Choice:
1
Enter Data:
movies

1.Insert
2.Remove
3.Show
Choice:
1
Enter Data:
books

1.Insert
2.Remove
3.Show
Choice:
3
Show contents of Queue:

movies  books
1.Insert
2.Remove
3.Show
Choice:
2
Removing Element From Queue!!!
Element Removed : movies

1.Insert
2.Remove
3.Show
Choice:
3
Show contents of Queue:

books
1.Insert
2.Remove
3.Show
Choice: 5